package com.shinji.tratu;

import java.util.ArrayList;

import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.jsoup.select.Elements;

import android.app.Activity;
import android.content.SharedPreferences;
import android.content.SharedPreferences.Editor;
import android.os.AsyncTask;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.text.Html;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.webkit.WebView;
import android.webkit.WebViewClient;
import android.widget.Button;
import android.widget.Spinner;
import android.widget.TextView;
import android.widget.Toast;

import com.google.android.gms.ads.AdRequest;
import com.google.android.gms.ads.AdView;
import com.google.android.gms.analytics.HitBuilders;
import com.google.android.gms.analytics.Tracker;

public class DicLookupFragment extends Fragment implements LookupAction {
	Spinner mSpinner;
	TextView mDicLookupResult;
	TextView mDicLookupKey;
	private Button gogoButton;
	private MainActivity mainActivity;
	private ArrayList<Word> listWords;
	String TAG = "DicLookupFragment", dataSource;
	private AdView mAdView;
	private WebView webView;
	private AudioPlayer audioPlayer;
	SharedPreferences mPref;
	Editor editor;
	boolean disableAd = false; // co vo hieu hoa quang cao khong
	// Create the search view
	private static DicLookupFragment instance;

	public static DicLookupFragment getInstance() {
		return instance;
	}

	@Override
	public void onActivityCreated(Bundle savedInstanceState) {
		// TODO Auto-generated method stub
		super.onActivityCreated(savedInstanceState);

	}

	@Override
	public void onAttach(Activity activity) {
		// TODO Auto-generated method stub
		super.onAttach(activity);
		mainActivity = (MainActivity) activity;
		Tracker t = ((AnalyticsSampleApp) mainActivity.getApplication())
				.getTracker(com.shinji.tratu.AnalyticsSampleApp.TrackerName.APP_TRACKER);
		t.setScreenName(TAG);
		t.send(new HitBuilders.AppViewBuilder().build());
		disableAd = ToastAdListener.isAdDisable(mainActivity);
	}

	@Override
	public void onCreate(Bundle savedInstanceState) {
		// TODO Auto-generated method stub
		super.onCreate(savedInstanceState);

	}

	@Override
	public View onCreateView(LayoutInflater inflater, ViewGroup container,
			Bundle savedInstanceState) {
		View layoutView = inflater.inflate(R.layout.dic_lookup_fragment,
				container, false);
		mAdView = (AdView) layoutView.findViewById(R.id.adView);
		if (disableAd) {
			mAdView.setVisibility(View.GONE);
			Log.i(TAG, "disable ad");
		} else {
			mAdView.setAdListener(new ToastAdListener(mainActivity));
			mAdView.loadAd(new AdRequest.Builder().build());
		}
		mDicLookupResult = (TextView) layoutView
				.findViewById(R.id.dic_lookup_result);
		mDicLookupKey = (TextView) layoutView.findViewById(R.id.dic_lookup_key);
		webView = (WebView) layoutView.findViewById(R.id.webView1);
		webView.setFocusableInTouchMode(false);
		webView.setFocusable(false);
		webView.setBackgroundColor(getResources().getColor(R.color.background));
		webView.setWebViewClient(new WebViewClient() {
			public boolean shouldOverrideUrlLoading(WebView view, String url) {
				Log.i(TAG, "click url " + url);
				return true;
			}
		});		
		mSpinner = (Spinner) layoutView.findViewById(R.id.spinner);
		audioPlayer = new AudioPlayer(mainActivity);
		gogoButton = (Button) layoutView.findViewById(R.id.gogo_button);
		instance = this;

		return layoutView;
	}

	@Override
	public void wantToLookup(String key) {
		int dicIndex = mSpinner.getSelectedItemPosition();
		String dicType = Constants.LIST_DIC[dicIndex];
		Log.i(TAG, "dicType = " + dicType);
		mDicLookupKey.setText(key);
		// reset cac view khi bat dau tim kiem
		mDicLookupResult.setText(getString(R.string.searching));
		gogoButton.setVisibility(View.GONE);
		webView.setVisibility(View.GONE);
		//
		Word result = Util.searchInListWordsByKeyAndDicType(listWords, key,
				dicType);
		if (result != null) {
			// neu da search tu truoc
			if (Constants.MOBILE_OR_NOT[dicIndex]) {
				mDicLookupResult.setVisibility(View.VISIBLE);
				mDicLookupResult
						.setText(Html.fromHtml(result.getSearchResult()));
				webView.setVisibility(View.VISIBLE);
			} else {
				webView.setVisibility(View.VISIBLE);
				webView.loadData(result.getSearchResult(),
						"text/html; charset=UTF-8", null);
				mDicLookupResult.setVisibility(View.GONE);
			}
			audioPlayer.setDataSource(result.getServerAudioLink());
			audioPlayer.setButton(gogoButton);
			setGogoButton(result);
		} else {
			mainActivity.showProgress();
			new LookupAsync().execute(key, String.valueOf(dicIndex));
		}

	}

	private class LookupAsync extends AsyncTask<String, String, Word> {
		Document doc;
		String word;
		int dicIndex;

		@Override
		protected Word doInBackground(String... params) {
			word = params[0];
			dicIndex = Integer.valueOf(params[1]);
			String dicType = Constants.LIST_DIC[dicIndex];
			String lookupLink = Util.getLookupLink(dicType, word,
					Constants.MOBILE_OR_NOT[dicIndex]);
			Log.i(TAG, "lookupLink = " + lookupLink);
			doc = lookupWord(lookupLink);
			if (doc != null) {
				Elements contents = doc.select("div#"
						+ Constants.LIST_DIV_ID[dicIndex]);
				// sSpanned s = Html.fromHtml(contents.html());
				Word wordRecord = new Word();
				String htmlString = contents.html();
				Log.i(TAG, htmlString);
				if (htmlString.contains(mainActivity
						.getString(R.string.result_not_found))) {
					Log.i(TAG, "not found");
					wordRecord
							.setSearchResult(getString(R.string.not_found_notice));
				} else {
					wordRecord.setSearchResult(htmlString);
				}
				String audioLink = findAudioLink(doc.html());
				wordRecord.setKey(word);
				wordRecord.setDicType(dicType);
				wordRecord.setSearchSucceed(true);
				if (audioLink != null) {
					wordRecord.setServerAudioLink(audioLink);
					dataSource = audioLink;
				} else {
					dataSource = "";
				}
				wordRecord.setServerAudioLink(dataSource);
				audioPlayer.setDataSource(dataSource);
				audioPlayer.setButton(gogoButton);
				wordRecord.setDicIndex(dicIndex);
				long wordId = mainActivity.getWordDatabase().createRecord(
						wordRecord);
				wordRecord.setId(wordId);
				return wordRecord;
			} else {
				return null;
			}
		}

		@Override
		protected void onPostExecute(Word result) {
			super.onPostExecute(result);
			mainActivity.hideProgress();
			if (doc != null) {
				if (Constants.MOBILE_OR_NOT[dicIndex]) {
					mDicLookupResult.setVisibility(View.VISIBLE);
					mDicLookupResult.setText(Html.fromHtml(result
							.getSearchResult()));
					webView.setVisibility(View.GONE);
				} else {
					webView.setVisibility(View.VISIBLE);
					webView.loadData(result.getSearchResult(),
							"text/html; charset=UTF-8", null);
					mDicLookupResult.setVisibility(View.GONE);
				}
				// /
				setGogoButton(result);

				// ////////////////////////////////////////////
				listWords.add(result);
				mainActivity.notifySearchDone();
			} else {
				mDicLookupResult.setText("");
				Toast.makeText(mainActivity, getString(R.string.search_error),
						Toast.LENGTH_SHORT).show();
			}
		}

		@Override
		protected void onPreExecute() {
			super.onPreExecute();
		}

		public Document lookupWord(String url) {
			try {
				Document doc = Jsoup.connect(url).data("query", "Java")
						.userAgent("CoRom/33.0.1750.154")
						.cookie("auth", "token").timeout(10000).get();
				// Elements contents = doc.select("div#content");
				Elements contents = doc.select("div#content");
				Log.i(TAG, "html content = " + contents.html());
				Log.i(TAG, "text content = " + contents.text());
				return doc;
			} catch (Exception e) {
				Log.i(TAG, "" + e.toString());
			}
			return null;
		}

	}

	private void setGogoButton(Word result) {
		if (result.getServerAudioLink() != null
				&& result.getServerAudioLink().length() > 0) {
			gogoButton.setVisibility(View.VISIBLE);
			gogoButton.setOnClickListener(new View.OnClickListener() {
				@Override
				public void onClick(View v) {
					Log.i(TAG, "clicked");
					audioPlayer.playAudio();
				}
			});
		}
	}

	@Override
	public void onPause() {
		super.onPause();
		if (!disableAd)
			mAdView.pause();
	}

	private String findAudioLink(String htmlString) {
		String firstPattern = "http://tratu.vcmedia.vn";
		String lastPattern = ".mp3";
		int index1 = htmlString.indexOf(firstPattern);
		if (index1 != -1) {
			int index2 = htmlString.indexOf(lastPattern, index1);
			String link = htmlString.substring(index1,
					index2 + lastPattern.length());
			Log.i(TAG, "link = " + link);
			return link;
		}
		return null;
	}

	@Override
	public void onResume() {
		Log.i(TAG, "onResume");
		super.onResume();
		disableAd = ToastAdListener.isAdDisable(mainActivity);
		if (disableAd) {
			mAdView.setVisibility(View.GONE);
			Log.i(TAG, "disable ad");
		} else {
			mAdView.setVisibility(View.VISIBLE);
			mAdView.resume();
		}
		listWords = mainActivity.getListWords();
		mainActivity.setLookupAction(this);
	}

	@Override
	public void onDestroy() {
		super.onDestroy();
		if (!disableAd)
			mAdView.destroy();
	}

	@Override
	public void onQueryTextChange(String newText) {
		// drawingWords = Util.searchInListWordsByKey(listWords, newText);
		// adapter.setListWords(drawingWords);
		// adapter.notifyDataSetChanged();
	}

}
